package the.broccoli.setting.interfaces.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.BusinessException;
import the.broccoli.setting.service.IFileService;
import the.broccoli.setting.vo.FileUploadVO;
import the.broccoli.setting.service.IParamsService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static the.broccoli.setting.constant.SettingConsts.FILE_UPLOAD_DIR;

/**
 * 附件操作控制器
 */
@RestController
@RequestMapping("/setting/file/")
public class FilesController {

	private Logger logger = LoggerFactory.getLogger(FilesController.class);

	@Resource
	private IParamsService paramsService;

	@Resource
	private IFileService fileService;

	/**
	 * <p>     
	 * Description: 附件上传
	 * </p>  
	 */
	@PostMapping("upload")
	public APIResult<List<FileUploadVO>> uploadFile(StandardMultipartHttpServletRequest multipartRequest) {
		String realPath = paramsService.getValue(FILE_UPLOAD_DIR);
		if (!StringUtils.hasText(realPath)) {
			throw BusinessException.withErrorCode("没有配置文件上传存储路径");
		}

		List<FileUploadVO> data = null;
		List<MultipartFile> fileList = multipartRequest.getFiles("file");
		if (!CollectionUtils.isEmpty(fileList)) {
			data = new ArrayList<>();

			for (MultipartFile file : fileList) {
				String fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				String fileNewName = IdWorker.getId() + "." + suffix;
				FileUploadVO fileUpload = new FileUploadVO();
				fileUpload.setFileName(fileName);
				fileUpload.setFileSize(String.valueOf(file.getSize()));
				fileUpload.setFileSuffix(suffix);
				fileUpload.setFileUrl(fileNewName);
				try {
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileNewName));
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
				data.add(fileUpload);
			}
		}
		return APIResult.success(data);
	}

	/**
	 * 附件下载
	 * @param response	响应信息
	 * @param url		附件存储地址
	 * @param name		附件名称
	 */
	@PostMapping("download")
	public void download(HttpServletResponse response, String url, String name) {
		String realPath = paramsService.getValue(FILE_UPLOAD_DIR);
		String path = realPath + "/" + url;
		String downLoadName = null;
		try {
			downLoadName = new String(name.getBytes("gbk"), "iso8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error(e.toString() + ":" + e.getMessage());
		}

		String suffix = "";
		if (StringUtils.hasText(url)) {
			int index = url.indexOf(".");
			if (index > -1) {
				suffix = url.substring(index);
			}
		}

		response.addHeader("Content-Type", "text/html; charset=utf-8");
		response.addHeader("Content-disposition", "attachment;filename=" + downLoadName + suffix);
		response.setContentType("octets/stream");
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");

		// 输出文件
		try {
			FileInputStream fileInputStream = new FileInputStream(path);
			OutputStream out = response.getOutputStream();
			int i = 0;
			while ((i = fileInputStream.read()) != -1) {
				out.write(i);
			}
			fileInputStream.close();
		} catch (Exception e) {
			logger.error(e.toString() + ":" + e.getMessage());
		}
	}

	/**
	 * 显示图片
	 * @param response
	 * @param fileUrl
	 * @throws IOException
	 */
	@GetMapping("output")
	public void output(HttpServletResponse response, @RequestParam("fileUrl") String fileUrl)
			throws IOException {
		String realPath = paramsService.getValue(FILE_UPLOAD_DIR);
		String path = realPath + "/" + fileUrl;

		ServletOutputStream out = null;
		FileInputStream ips = null;
		try {
			//获取图片存放路径
			ips = new FileInputStream(new File(path));
			response.setContentType("multipart/form-data");
			out = response.getOutputStream();
			//读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = ips.read(buffer)) != -1){
				out.write(buffer,0,len);
			}
			out.flush();
		} catch (Exception e){
			logger.error(e.toString() + ":" + e.getMessage());
		} finally {
			if (out != null) {
				out.close();
			}
			if (ips != null) {
				ips.close();
			}

		}
	}

	/**
	 * 附件预览
	 * @param fileName	附件名称
	 * @param suffix	附件后缀
	 * @param response	响应信息
	 */
	@GetMapping(value = "preview/{fileName}/{suffix}")
	public void preview(
			@PathVariable("fileName") String fileName,
			@PathVariable("suffix") String suffix,
			HttpServletResponse response) {
		String realPath = paramsService.getValue(FILE_UPLOAD_DIR);
		String path = realPath + "/" + fileName + "." + suffix;

		File file = new File(path);
		byte[] data = null;
		try {
			FileInputStream input = new FileInputStream(file);
			data = new byte[input.available()];
			input.read(data);
			response.getOutputStream().write(data);
			input.close();
		} catch (Exception e) {
			logger.error("文件预览处理异常：" + e.getMessage());
		}
	}
	
}
